package org.java.net.socket;

import java.net.*;
import java.io.*;
import java.util.*;
public class Server4{
  private ServerSocket server;
  Vector sManager=new Vector();
  Random rnd=new Random();
  public Server4(){}
  void startServer(){
    try{
      server=new ServerSocket(7777);
      System.out.println("服务器套接字已经被创建.");
      while(true){
        Socket socket=server.accept();
        System.out.println("已经与客户机连接.");
        new KBBCom_Thread(socket).start();
        sManager.add(socket);
        System.out.println("当前客户机连接数: "+sManager.size());
      }
    }catch(Exception e){
      System.out.println(e); 
    }
  }
  public static void main(String[] args){
    Server4 server=new Server4();
    server.startServer();
  }
  class KBBCom_Thread extends Thread{
    Socket socket;
    private DataInputStream reader;
    private DataOutputStream writer;
    KBBCom_Thread(Socket socket){
      this.socket=socket;
    }
    public void run(){
      try{
        reader=new DataInputStream(socket.getInputStream());
        writer=new DataOutputStream(socket.getOutputStream());
        String msg;
        while((msg=reader.readUTF())!=null){
          if(msg.equals("OK")){
            writer.writeInt(rnd.nextInt(3));
            writer.flush();
          }
        }
      }catch(Exception se){
      }finally{  
        try{
          sManager.remove(socket);
          if(reader!=null) reader.close();
          if(writer!=null) writer.close();
          if(socket!=null) socket.close();
          reader=null; writer=null; socket=null;

          System.out.println("客户机离开.");
          System.out.println("当前客户机连接数: "+sManager.size());
        }catch(Exception e){}
      }
    }
  }
}